package com.tm.servicemsm.controller;

import com.tm.servicemsm.demos.R;
import com.tm.servicemsm.service.MsmService;
import com.tm.servicemsm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/send/{phone}")
    public R sendMsm(@PathVariable String phone){
        String code= redisTemplate.opsForValue().get(phone);
        if(!(Objects.isNull(code))){
            return R.ok().code(Integer.parseInt(code));
        }
         code = RandomUtil.getSixBitRandom();
        Map<String,Object> map=new HashMap<String ,Object>();
        map.put("code",code);
        boolean isSend= msmService.send(map,phone);
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        }
        return R.ok();
    }

    //验证验证码是否正确
    @GetMapping("/login")
    public R login(String phone,String code){
        //从redis中取出来

        if(!(Objects.isNull(code))){
            String _code = redisTemplate.opsForValue().get(phone);
          if(code.equals(_code)){
              return R.ok().message("登录成功！");
          }
          else {
              return R.error().message("验证码不匹配");
          }
        }
        return R.error().message("验证码有误,请重新输入！");
    }
}
